var lesson_id='';//课程ID
var _this='';
var enterTimes='';
var onthisTime='';
var calender = {
	CHOOSE_DATE: "",
	TODAY_DATE: "",
	IS_LOADING: false,
	/**
	 * 改变当前选择时间
	 * @param {object} obj 当前控件（应该是span）
	 */
	changeFocus: function(obj) {
		var  Datenow = new Date();
		var getdate=Datenow.getDate();
		var getmonth=Datenow.getMonth()+1;
		
		var thisYM=$("#thisYM").html();
		var str=thisYM.toString();
		//var newStr=str.substring(str.length,str.length-3).substring(0,2);
		//if(newStr==getmonth){
			//if(obj.innerHTML<getdate){
				//return;
			//}
		//}
		
		
		var doc = document,
			fDate = obj.getAttribute("full-date"),
			pre = doc.querySelector(".focus"),
			preClass, thisClass,
			arr = fDate.split("-");
			$.each($(".classTimes .col-xs-2"),function(){
		      $(this).removeClass("on");
	        })
	        
	        var newObj=$(obj);
			newObj.parents("td").find("span.focus").removeClass("focus");
	        
		doc.getElementById("thisYM").innerText = arr[0] + "年" + arr[1] + "月";
		if(pre != null) {
			preClass = pre.getAttribute("class");
			preClass = preClass.replace("focus", "");
			pre.setAttribute("class", preClass);
		}
		thisClass = obj.getAttribute("class");
		obj.setAttribute("class", thisClass + " focus");
		// 改变全局变量的值
		calender.CHOOSE_DATE = obj.getAttribute("full-date");
	},
	/**
	 * 改变月份
	 * @param {number} type 递增为1，递减为-1
	 */
	changeMonth : function(type){
		var doc = document, thisWeek,//周几
			thisYM = doc.getElementById("thisYM").innerText,// 格式为yyyy年mm月，如2014年11月
			thisYear = thisYM.substr(0, 4),// 取yyyy
			thisMonth = thisYM.substr(5, 2),// 取mm
			fDate,// 格式：yyyy-MM-dd
			choDate = new Date(),// 要跳转到的日期
			curDate = new Date();// 当前所在页面的日期
		choDate.setFullYear(thisYear, (thisMonth-1), 1);// 该方法的第二个参数，月份是从0开始的
		choDate.setMonth(choDate.getMonth() + type);// 修改日期
		thisYear = choDate.getFullYear();
		thisMonth = choDate.getMonth() + 1;
		thisWeek = choDate.getDay();
		if(thisMonth < 10) {
			thisMonth = "0" + thisMonth;
		}
		
		doc.getElementById("thisYM").innerText = thisYear + "年" + thisMonth + "月";
		// 获取当前显示这天日期
		fDate = doc.getElementById("week" + thisWeek).getAttribute("full-date");
		var dateArr = fDate.split("-"), gapDate;
		curDate.setFullYear(dateArr[0], (dateArr[1]-1), dateArr[2]);
		// 获取要显示的月份一日这天距离当前显示这天日期的天数。可以是正负
		gapDate = (choDate.getTime() - curDate.getTime()) / (1000*60*60*24);
		// 执行改变日期
		calender.changeDate(gapDate);
	},
	/**
	 * 滑动改变日期
	 * @param {number} type 递增正数，递减为负数；可自行修改。
	 */
	changeDate: function(type) {
		var doc = document;
		// 去除之前的focus样式和today样式
		var focus = doc.querySelector(".focus"),
			focusClass;
		if (focus != null) {
			focusClass = focus.getAttribute("class");
			focusClass = focusClass.replace("focus", "");
			focus.setAttribute("class", focusClass);
		}
		var today = doc.querySelector(".today"),
			todayClass;
		if (today != null) {
			todayClass = today.getAttribute("class");
			todayClass = todayClass.replace("today", "");
			today.setAttribute("class", todayClass);
		}

		// 改变日期
	
		nowDate = new Date();
		nowYear = nowDate.getFullYear();
		var nowMoth=nowDate.getMonth()+1;
		if(nowMoth<10){
			var nowMoth="0"+nowMoth;
		}
		//var prevNowDate=nowYear + nowMoth;
		//var nowMothStr=doc.getElementById("thisYM").innerText;
		//var nowNewMoth=nowMothStr.replace(/[^0-9]/ig,"");
		
		//if(nowNewMoth<=prevNowDate&&type==-7){
			//return;
		//}
		$("#week6").addClass("focus");
		for (var i = 0, infor, preDate, fdate; i < 7; i++) {
			infor = doc.getElementById("week" + i);
			preDate = infor.getAttribute("full-date");
			var arr = preDate.split("-"),
				preYear = arr[0],
				preMonth = arr[1],
				preDate = arr[2];
			preMonth = preMonth - 1;
			var now = new Date();
			now.setFullYear(preYear, preMonth, preDate);
			now.setDate(now.getDate() + type);
			var year = now.getFullYear(),
				month = now.getMonth() + 1,
				thisDate = now.getDate();

			if (month < 10) {
				month = "0" + month;
			}
			if (thisDate < 10) {
				thisDate = "0" + thisDate;
			}
			
			// 如果最后一天的月份不等于之前月份
			if(i == 6){

				if (month != (preMonth + 1) || year != preYear) {
					doc.getElementById("thisYM").innerText =
						year + "年" + month + "月";
				}
			}
			
			infor.innerText = thisDate;
			fdate = year + "-" + month + "-" + thisDate;
			infor.setAttribute("full-date", fdate);
			// 判断是否滑动回到选择的时间
			if (fdate == calender.CHOOSE_DATE) { // 上次选择的时间
				var thisClass = infor.getAttribute("class");
				infor.setAttribute("class", thisClass + " focus");
			}
			// 判断是否滑动回到当前的时间
			if (fdate == calender.TODAY_DATE) { // 今天时间
				var thisClass = infor.getAttribute("class");
				infor.setAttribute("class", thisClass + " today");
			}
		}

	
	},
	mouseDown: function(obj, thisX){	
		obj.onmousemove = function(){
			calender.mouseMove(thisX);
		};
		obj.onmouseup = function(){
			calender.mouseUp(this);
		};
		obj.onselectstart = function(){
			return false;
		};		
	},
	mouseMove: function(lastX){
		var thisX = event.clientX;
		if(thisX - lastX > 30 && !calender.IS_LOADING){
			calender.IS_LOADING = true;
			calender.changeDate(-7);
		}else if(thisX - lastX < -30 && !calender.IS_LOADING){
			calender.IS_LOADING = true;
			calender.changeDate(7);
		}
	},
	mouseUp : function(obj){	
		obj.onmousemove = null;
		obj.onmouseup = null;
		calender.IS_LOADING = false;
	}
};

/**
 * 自运行的JS函数，用来构造日历的初始样式
 */
(function() {
	/**********************日历初始化开始************************/
	// 填充日期
	var preDate = new Date(),
		nextDate = new Date(),
		now = new Date(),
		week = now.getDay(),
		thisMonth = now.getMonth() + 1, // 显示月份
		thisDate = now.getDate(), // 显示日期
		doc = document,
		thisYM = doc.getElementById("thisYM");

	// 今天的月份
	if (thisMonth < 10) {
		thisMonth = "0" + thisMonth;
	}
	thisYM.innerText = now.getFullYear() + "年" + thisMonth + "月";
	// 今天日期，小于10前面补0
	if (thisDate < 10) {
		thisDate = "0" + thisDate;
	}
	doc.getElementById("week" + week).innerText = thisDate;
	doc.getElementById("week" + week).setAttribute("class", "today focus");
	// 默认初始化时，选择的时间为当前时间
	calender.CHOOSE_DATE = now.getFullYear() + "-" + thisMonth + "-" + thisDate;
	calender.TODAY_DATE = calender.CHOOSE_DATE;
	doc.getElementById("week" + week).setAttribute("full-date", calender.CHOOSE_DATE);
	// 大于当前天
	for (var i = week + 1; i < 7; i++) {
		nextDate.setDate(nextDate.getDate() + 1);
		thisMonth = nextDate.getMonth() + 1;
		if (thisMonth < 10) {
			thisMonth = "0" + thisMonth;
		}
		thisDate = nextDate.getDate();
		if (thisDate < 10) {
			thisDate = "0" + thisDate;
		}
		doc.getElementById("week" + i).innerText = thisDate;
		doc.getElementById("week" + i).setAttribute("full-date",
			nextDate.getFullYear() + "-" + thisMonth + "-" + thisDate);
	}
	// 小于当前天
	for (var i = week - 1, thisMonth; i >= 0; i--) {
		preDate.setDate(preDate.getDate() - 1);
		thisMonth = preDate.getMonth() + 1;
		if (thisMonth < 10) {
			thisMonth = "0" + thisMonth;
		}
		thisDate = preDate.getDate();
		if (thisDate < 10) {
			thisDate = "0" + thisDate;
		}
		doc.getElementById("week" + i).innerText = thisDate;
		doc.getElementById("week" + i).setAttribute("full-date",
			preDate.getFullYear() + "-" + thisMonth + "-" + thisDate);
	}
	/**********************日历初始化结束************************/

	// 给每个日期增加点击事件
	var spans = doc.getElementsByTagName("span");
	for (var i = 0, len = spans.length; i < len; i++) {
		if (spans[i].getAttribute("id") &&
			spans[i].getAttribute("id").indexOf("week") != -1) {
			spans[i].onclick = function(){
				calender.changeFocus(this);
			};
		}
	}
		
	// 给月份添加左右点击事件
	doc.getElementById("preM").onclick = function(){
		
		//nowDate = new Date();
		//nowYear = nowDate.getFullYear();
		//var getdate=nowDate.getDate();
		//var ongetdate=$("#week0").html();
		//var nowMoth=nowDate.getMonth()+1;

		//if(nowMoth<10){
		 // var nowMoth="0"+nowMoth;
		//}
		//var prevNowDate=nowYear + nowMoth;
		//var nowMothStr=doc.getElementById("thisYM").innerText;
		//var nowNewMoth=nowMothStr.replace(/[^0-9]/ig,"");
		//if(nowNewMoth<=prevNowDate){
			//return;
		//}
		
		calender.changeMonth(-1);// 减少月
		$("#week6").addClass("focus");
	};
	
	// 给月份添加左右点击事件
	doc.getElementById("nextM").onclick = function(){
		calender.changeMonth(1);// 增加月
		$("#week6").addClass("focus");
	};
	

	// 如果移动端使用，可以使用下列代码

	//doc.getElementById("cal_week").addEventListener("touchmove", function() {
		//calender.changeDate(7); // 增加日期
		//return;
	//}, false);
	
	
})();
//选择上课时间
var indexArr=[];
function sortNumber(a,b)
{
 return a - b
}


$(".classTimes .col-xs-2").on("click",function(){
	if($(this).index()>25){
		return;
	}
    if($(this).prev().hasClass("on") && $(this).next().hasClass("on")){
    	//$(this).removeClass("on");
		$(this).nextAll().each(function(){
			$(this).removeClass("on");
			indexArr=[];
		})
		$(this).prevAll().each(function(){
			if($(this).hasClass("on")){
				indexArr.push($(this).index());
			}
		})
		
		indexArr=indexArr.sort(sortNumber);
		console.log(indexArr);
		return;
	
	 }
	$(this).toggleClass("on");
	if($(this).hasClass("on")){
		var index=$(this).index();
		indexArr.push(index);
		var newindexArr=indexArr.sort(sortNumber);
		var numIndexArr=[];
		//console.log(newindexArr)
		if(newindexArr.length>=2){
		  for(var i=newindexArr[0];i<=newindexArr[newindexArr.length-1];i++){
			  numIndexArr.push(i);
		  }
		}
		
		if(numIndexArr.length>=2){
		    for(var j=0;j<numIndexArr.length;j++){
		    	$(".classTimes .col-xs-2").each(function(){
		    		if($(this).index()==numIndexArr[j]){
		    			$(this).addClass("on");
		    		}
		    	})
		    }
		}
		console.log(indexArr);
	}else{
		indexArr=[];
		$(".classTimes .col-xs-2").each(function(){
    		if($(this).hasClass("on")){
    			indexArr.push($(this).index())
    		}
    	})
    	console.log(indexArr);
		
	}	
	
	//console.log(indexArr);
	
})
$("#timeSlecetOk").on("click",function(){
	  var sult='';
	  var ArayyclassTimes=[];
	  var classTimes='';
	  var classWeek='';
	  $.each($(".classTimes .col-xs-2"),function(){
		if($(this).hasClass("on")){
			sult=true;	
		}	
	  })
	  if(!sult){
		 alert("请选择课时"); 
		 return;
	  }
	  var i=0; 
	  $.each($(".classTimes .col-xs-2"),function(){ 
		if($(this).hasClass("on")){
			ArayyclassTimes[i]=$(this).find("span:first").html();
			ArayyclassTimes[i+1]=$(this).find("span:last").html();
			i++;
			//$(this).off("click");
			//$(this).addClass("redOn");
		}
	  })
	  classTimes=ArayyclassTimes[0];
	  $("#cal_week span").each(function(){
		  if($(this).hasClass("focus")){
			classWeek=$(this).html();
		  }
	  })
	  var classDate=$("#thisYM").html().replace("年","-").replace("月","-");	
	  var classTimesOk= classDate + classWeek+" " + classTimes+"~" +classDate + classWeek+" "+ArayyclassTimes[ArayyclassTimes.length-1];
	  var startTime=classDate + classWeek+" " + classTimes + ":"+"00";
	  var endTime=classDate + classWeek+" "+ArayyclassTimes[ArayyclassTimes.length-1] + ":"+"00";
	  var varTime=startTime + "~" + endTime;//写入input
	  _this.val(varTime);//排课传值
	  startTime=get_unix_time(startTime);
	  endTime=get_unix_time(endTime);
	  enterTimes={"startTime":startTime,"endTime":endTime};

	  $.each($(".classTimes .col-xs-2"),function(){
		$(this).removeClass("on");
	  })
	  
	//格式时间戳
	function get_unix_time(dateStr)
    {
      var newstr = dateStr.replace(/-/g,'/'); 
      var date =  new Date(newstr); 
      var time_str = date.getTime().toString();
      var times=time_str.substr(0, 13);
      return times;
    }
	  
	  var contrastYear=$("#thisYM").html();
	  var contrastMh=$("#thisYM").html();
	  contrastYear=contrastYear.substring(0,4);//获取选择的年
	  var contrastMh=contrastMh.substring(5,7);//获取选择的月
	  var contrastDate='';//获取选择的日
	  $("#cal_week span").each(function(){
		  if($(this).hasClass("focus")){
			  contrastDate=$(this).html(); 
		  }
	  })

	  var Datenow=new Date();
	  var getyear=Datenow.getFullYear();
	  var getmonth=Datenow.getMonth()+1;
	  if(getmonth<10){
		  getmonth='0' + getmonth; 
	  }
	  var getdate=Datenow.getDate();
	  
	 
	  
	  if(contrastYear<getyear){
		  alert("请选择正确的年份");
		  indexArr=[];
		  return;
	  }else if(contrastYear>getyear){
		  $(".classCalendar").hide(200);//隐藏排课页面 
		  return;
	  }else if(contrastYear=getyear){
	  
		  if(contrastYear>=getyear){
		    if(contrastMh<getmonth){
			  alert("请选择正确的月份");
			  indexArr=[];
			  return;
		    }
		    if(contrastMh==getmonth){
		    	if(contrastDate<getdate){
		    	  alert("请选择正确的日期");
		    	  indexArr=[];
		  		  return;
		    	}
		    }
		    
		  }
	  }
	  
	  $(".classCalendar").hide(200);//隐藏排课页面
	  indexArr=[];
	  $(".ui-page").css({"overflow-y":"inherit"});
	 
      
})

function classNumber(){
  var n=$("#slectclassNumber").val();
  if(n>30){
	  alert("课节数量请小于30");
	  $("#slectclassNumber").val("");
	  return;
  }
  $(".classNodeWrap").remove();
  for(var j=0;j<n;j++){
	  var classNode=$('<div class="classNodeWrap">'+
			  '<div class="row classNode">'+'<div class="col-xs-5" style="margin-top:7px">'+
			  '第'+'<span class="classNodeNum">'+'</span>'+(j+1)+'节:'+'上课时间：'+'</div>'+'<div class="col-xs-7 _input">'+'<input type="text" data-role="none" name="classNodeNum" placeholder="年月日时-年月日时" onclick="showTime(this)" readonly="readonly">'+
			  '</div>'+'</div>'+'</div>');
	  $(classNode).appendTo($("#classNodeOuter")); 
	  classNode='';
  }
  
}

function showTime(thisClasst){
	_this=$(thisClasst);
	$(".classCalendar").show(200);
	$(document).scrollTop(0);
}

//显示排课时间页面
function showSlectLesson(lesson_idN,_this){
	$(".ui-page").animate({'scrollTop':0});
	
	var whiteBg=$('<div style="position:fixed;background-color:#fff;height:100%;width:100%;z-index:99" id="whiteBg">' + '</div>');
	whiteBg.appendTo($("body"));
	if(_this){
		$(".ui-page").css({"overflow-y":"hidden"});
		_this=$(_this);
		if(_this.parents(".boxli").prev()){
		  if(_this.parents(".boxli").prev().find(".boxrightInfos2").find("div").hasClass('timebtn')){
			alert("请按课节顺序排课");
			return;
		  }
	    }
	}
	lesson_id=lesson_idN;
	$(".yhx_kejieWrap").show(200);
	$("#whiteBg").remove();
	$(document).scrollTop(0);
}

//设置课节时间
$(".yhx_enterKj").on("click",function(){
	 if($(this).hasClass("timebtn")){
		 $(this).parents(".boxli").find(".okTime").html(classTimeListAry);
	 }
	 //修改课程时间
	 if($(this).attr("id")=="timeId1"){
		if($(".classNodeWrap ._input input").val()==''){
		  alert("请设置课节时间");
		  return;	
	    }
	  $.ajax({
		    type: 'post',
		    url: ajaxUrl + "/app/course/setLessonTime?lesson_id=" + lesson_id + "&start_time=" + enterTimes.startTime + "&end_time=" + enterTimes.endTime,
		    data:'',//传给后台的数据，多个参数用&连接
		    dataType: 'JSON',
		    success: function(msg){
		    	if(msg.data.result==1){
		    		alert("排课成功");
		    	}else{
		    		alert("出错啦！");
		    		return;
		    	}
		    	notDischargingCourse();//更新未排课
		    	waitClass();//更新未上课
		   	    $(".yhx_kejieWrap").hide(200);
		   	 $(".ui-page").css({"overflow-y":"inherit"});
		   	   _this.val('');
		   	   window.location.href=window.location.href;
		    }
	  })
	 }
	  //发布课程班课排课时间
	  if($(this).attr("id")=="timeId2"){
		  var temp=true;
		  if($("#slectclassNumber").val()==''){
			  alert('请设置课节');
			  return;
		  }
		  var classTimeListAry=[];//保存可节时间
		  $(".classNodeWrap").each(function(){  
			if($(this).find("input").val()==''){
			  temp=false;
		    }  
			classTimeListAry.push($(this).find("input").val());
		  })
		  if(temp){
		    $("#classTimeList").val(classTimeListAry);
		    $("#writeClassTime").attr("placeholder","已设置");
		    $(".classNodeWrap").remove();
		    $("#slectclassNumber").val('');
		    $(".yhx_kejieWrap").hide(200);
		    $(".ui-page").css({"overflow-y":"inherit"});
		  }else{
			  alert("请设置课节时间");
			  return false;
		  }
		  
		  var timeArrList=[];
		  for(var i=0;i<classTimeListAry.length;i++){
			  timeArrList.push(classTimeListAry[i].substring(0,10).replace("-","").replace("-",""));
		  }
		  timeArrList=timeArrList.sort(sortNumber);
		  onthisTime=timeArrList[timeArrList.length-1];
	  }
	
})



$("#closePK").on("click",function(){
	$(".classCalendar").hide();
	indexArr=[]
})
$("#closeAddClass").on("click",function(){
	$(".yhx_kejieWrap").hide();
	$("#whiteBg").remove();
	$(".ui-page").css({"overflow-y":"inherit"});
})
$("#classSelectDate").on("click",function(){
	$("#classSelectDateInput").focus();
})